package com.ys.utils.base.j2se;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESOperator {
    /*
     * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
     */
    public static String KEY = "!QA2Z@w1sxO*(-8L";
    public static String VECTOR = "!WFNZFU_{H%M(S|a";
    private static AESOperator instance = null;

    private AESOperator() {

    }


    public static AESOperator getInstance() {
        return Nested.instance;
    }
    //于内部静态类只会被加载一次，故该实现方式时线程安全的！
    static class Nested {
        private static AESOperator instance = new AESOperator();
    }

    /**
     * 加密
     *
     * @param content
     * @return
     * @throws Exception
     */
    public String encrypt(String content) throws Exception {
        return encrypt(content, KEY, VECTOR);
    }
    /**
     * 加密
     *
     * @param content
     * @return
     * @throws Exception
     */
    public String encrypt(String content,String key) throws Exception {
        return encrypt(content, key, VECTOR);
    }

    /**
     * 加密
     *
     * @param content
     * @param key
     * @param vector
     * @return
     * @throws Exception
     */
    public String encrypt(String content, String key, String vector) throws Exception {
        if (key == null) {
            return null;
        }
        if (key.length() != 16) {
            return null;
        }
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(content.getBytes("UTF-8"));

        String str = Base64.encodeBase64String(encrypted);
        str = str.replaceAll("\\n", "").replaceAll("\\r", "");
        //注意：linux环境下加密时，会自动补\r \n到加密数据里面
//        str = str.replaceAll("\r\n", "");
//        str = str.replaceAll("\n", "");
        return str;// 此处使用BASE64做转码。

    }
}
